<?php
/**
 * Notes: 预警系统参数配置
 * Author: chenjie
 * @return
 * Date: 2021/11/26
 */

namespace App\Repositories;


use App\Exceptions\BasicException;
use App\Models\MainDB\Erm\ErmConfig;
use App\Enums\ErmEnum;

class ErmConfigRepository
{
    public function getConfigList()
    {
        $res = app('model_erm_config')
            ->from(app('model_erm_config')->getTable() . ' as r')
            ->selectRaw('r.id,r.name,r.status,r.update_time,a.admin_name,r.key')
            ->join(app('model_admin')->getTable() . ' as a', 'r.operator_id', '=', 'a.admin_id')
            ->get()->toArray();

        $list = [];
        $gray = [
            ErmEnum::USER_WX_PAY_OPEN_ID_LIMIT,
            ErmEnum::USER_ALI_PAY_BUYER_ID_LIMIT,
            ErmEnum::AUTO_GRAY_DEVICE_RISK,
            ErmEnum::AUTO_GRAY_RECHARGE,
            ErmEnum::AUTO_GRAY_BACKPACK,
            ErmEnum::USER_WX_PAY_OPEN_ID_LIMIT_BLACK,
            ErmEnum::USER_ALI_PAY_BUYER_ID_LIMIT_BLACK,
            ErmEnum::WITHIN_SAME_ORDER,
            ErmEnum::DEVICE_NUM,
        ];
        $rule = [
            ErmEnum::AUTO_REMOVE_GRAY_LIST,
            ErmEnum::AUTO_ADD_BLACK_LIST,
            ErmEnum::WHITE_LIMIT_NUM,
        ];
        $limit = [
            ErmEnum::ALI_PAY_LINK_EXPIRE_TIME,
            ErmEnum::WAIT_PAY_ORDER_LIMIT,
            ErmEnum::RECHARGE_NEED_CHECK,
            ErmEnum::RECHARGE_COUNT_NEED_CHECK,
            ErmEnum::TEST_USER_LIST,
            ErmEnum::ERM_SWITCH,
            ErmEnum::PUSH_NOTICE,
            ErmEnum::HINT_CONTENT,
        ];

        foreach ($res as $item) {
            if (in_array($item['key'],$gray)) {
                $list['gray'][] = $item;
            }
            if (in_array($item['key'],$rule)) {
                $list['rule'][] = $item;
            }
            if (in_array($item['key'],$limit)) {
                $list['limit'][] = $item;
            }
        }

        return $list;
    }

    public function getConfigDetail(int $id)
    {
        $detail = app('model_erm_config')->where(['id'=>$id])->first();

        if(empty($detail))
        {
            return [];
        }

        /*测试用户ID配置转为user_code显示*/
        if ($detail['key'] == ErmEnum::TEST_USER_LIST) {
            $user_code_arr = explode(',', $detail['value']);
            $user_ids = app('model_user_data')->whereIn('user_id', $user_code_arr)->pluck('user_code')->toArray();
            if ($user_ids) {
                $detail['value'] = implode(',', $user_ids);
            }
        }

        $info = [
            'key' => $detail['key'],
            'status' => $detail['status'],
            //'config_is_obj' => is_numeric($detail['value']) ? 0 : 1,
            'config' => is_numeric($detail['value']) ? $detail['value'] : json_decode($detail['value'], true)
        ];

        return $info;
    }

    public function edit(array $param)
    {
        $detail = app('model_erm_config')->where(['id'=>$param['id']])->first();
        if(!$detail)
        {
            throw new BasicException(10001, '数据不存在');
        }
        if (!isset($param['config']) && $detail['key'] == ErmEnum::TEST_USER_LIST) {
            $param['config'] = '';
        }
        if($detail['key'] != ErmEnum::TEST_USER_LIST&&!isset($param['config'])){
            throw new BasicException(10001, 'config 不能为空。');
        }

        $detail['value'] = $this->formatData($detail['key'], $param['config']);
        $detail['status'] = $param['status'];
        $detail['operator_id'] = $param['operator_id'];
        $detail['update_time'] = time();

        /*测试用户ID配置转为user_id添加*/
        if ($detail['key'] == ErmEnum::TEST_USER_LIST) {
            $user_code_arr = explode(',', $param['config']);
            $user_ids = app('model_user_data')->whereIn('user_code', $user_code_arr)->where('user_code', '!=', 0)->pluck('user_id')->toArray();
            if ($user_ids) {
                $detail['value'] = implode(',', $user_ids);
            }
        }

        return $detail->save();
    }

    private function formatData($key, $config)
    {
        switch ($key)
        {
            case 'WAIT_PAY_ORDER_LIMIT' :
                $tmp = json_decode($config, true);
                $value = [
                    'seconds' => $tmp['seconds'] ?? 0,
                    'order_num' => $tmp['order_num'] ?? 0,
                ];

                if($value['seconds'] < 1 || $value['order_num'] < 1)
                {
                    throw new BasicException(10001, '参数必须大于0');
                }

                $value = json_encode($value);
                break;
            case 'AUTO_REMOVE_GRAY_LIST' :
                $tmp = json_decode($config, true);
                $value = [
                    'recharge' => $tmp['recharge'] ?? 0,
                    'consume' => $tmp['consume'] ?? 0,
                    'withdraw' => $tmp['withdraw'] ?? 0,
                    'convert' => $tmp['convert'] ?? 0,
                ];

                if(!in_array($value['recharge'], [0,1]) || !in_array($value['consume'], [0,1]) || !in_array($value['withdraw'], [0,1]) || !in_array($value['convert'], [0,1]))
                {
                    throw new BasicException(10001, '参数值必须是0或1');
                }

                $value = json_encode($value);
                break;
            default :
                $value = $config;
                break;
        }

        return $value;
    }

    public function getConfig($key)
    {
        $rule = app('model_erm_config')->where([
            'status' => 0,
            'key' => $key,
        ])->first();

        return $rule;
    }
}